import {createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import Layout from '@/views/layout'
import NotFund from '@/views/404'
import Login from '@/views/login'
import store from '@/store/index'
import {getMenu} from "@/api";
import addRoutesDynamically from "@/router/addRoutes";

const routes = [
    {
        path: '/',
        redirect: '/layout',
    },
    {
        path: '/layout',
        name: 'layout',
        component: Layout,
        children: []
    },
    {
        path: '/login',
        component: Login
    },
    {
        path: '/:pathMatch(.*)',
        component: NotFund
    }
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})
router.beforeEach(async (to, from, next) => {
    const {token, menus} = store.state
    const hasRoute = router.hasRoute(to.name)
    //非登录页判断token
    if (to.path !== '/login') {
        //判断token
        if (!token) {
            store.commit('loginout')
            next({path: '/login', redirect: true})
        }
        //如果本地没有缓存路由，请求路由列表
        if (menus.length === 0) {
            let list = await getMenu()

            store.commit('set_menus', list)
            addRoutesDynamically(router, list)
            next({path: '/index', redirect: true})
        } else {
            if (!hasRoute) {
                // 如果该路由不存在，可能是动态注册的路由，它还没准备好，需要再重定向一次到该路由
                store.commit('set_current_route', to.path)
                next({...to, replace: true})
            } else {
                store.commit('set_current_route', to.path)
                next()
            }
        }
    }
    next()
})

export default router
